package cn.peng.stu4teach.pages.main;

import android.app.Application;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.AndroidViewModel;

import com.google.android.material.navigation.NavigationBarView;

import cn.peng.stu4teach.R;
import cn.peng.stu4teach.pages.home.HomeFragment;
import cn.peng.stu4teach.pages.my.MyFragment;
import cn.peng.stu4teach.pages.todo.TodoFragment;

/**
 * 首页使用的Vm
 */
public class MainVm extends AndroidViewModel {
    public MainVm (@NonNull Application application) {
        super(application);
    }

    /**
     * 展示 fragment 到指定的视图容器中
     */
    public void showFragment (@NonNull Fragment pFragment, @NonNull FragmentManager pFragmentManager) {
        // 开始事务
        FragmentTransaction transaction = pFragmentManager.beginTransaction();
        // 替换容器中的Fragment
        transaction.replace(R.id.fl_container, pFragment);
        // 添加到回退栈，如果需要的话
        //transaction.addToBackStack(null);
        // 提交事务
        transaction.commit();
    }

    /**
     * 获取选中事件的监听器
     */
    public NavigationBarView.OnItemSelectedListener getBtmNvItemSelectedListener (@NonNull FragmentManager pFragmentManager) {
        return new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected (@NonNull MenuItem item) {
                Fragment selectedFragment = null;
                int itemId = item.getItemId();
                if (itemId == R.id.action_home) {
                    selectedFragment = HomeFragment.newInstance();
                } else if (itemId == R.id.action_todo) {
                    selectedFragment = TodoFragment.newInstance();
                } else if (itemId == R.id.action_my) {
                    selectedFragment = MyFragment.newInstance();
                } else {
                    return true;
                }

                showFragment(selectedFragment, pFragmentManager);

                // 事件是否已经被处理
                return true;
            }
        };
    }
}

